package com.aiju.cash.ui.member;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.cash.R;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.api.MemberApi;
import com.aiju.cash.core.event.MemberEvent;
import com.aiju.cash.ui.member.adater.MemberAdapter;
import com.aiju.cash.ui.member.entity.Member;
import com.aiju.common.event.EventBusHandler;
import com.aiju.common.event.EventCenter;
import com.aiju.support.recyclerView.DividerItemDecoration;
import com.aiju.utils.T;
import com.aiju.utils.Util;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.loadmore.SwipeRefreshHelper;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * @author: 佐为
 * @date: 2017-02-20 15:59
 * @version: V1.0
 * @Description: 会员列表
 */
public class MemberManagerActivity extends BaseTitleActivity implements View.OnClickListener {

    private int currentNum = 1;
    private int pageSize = 10;
    private View empty;
    private RecyclerView recyclerviewTeams;

    private SwipeRefreshLayout mSwipeRefreshLayout;
    private SwipeRefreshHelper mSwipeRefreshHelper;
    private RecyclerAdapterWithHF mAdapter;

    private List<Member> memberCards = new ArrayList<>();
    private MemberAdapter mBlotterAdater;

    private boolean isLoad;
    private boolean isRefresh;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member_manager);
        setCenterTitle("会员管理");

        ImageView right = new ImageView(this);
        right.setImageResource(R.mipmap.icon_search_white);
        mAiJuTitleBarView.setCustomizedRightView(right);
        mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(MemberSearchActivity.class);
            }
        });
        findViewById(R.id.tv_member_tip).setOnClickListener(this);
        findViewById(R.id.iv_member_tip_close).setOnClickListener(this);
        findViewById(R.id.btn_member_add).setOnClickListener(this);
        findViewById(R.id.btn_member_card_add).setOnClickListener(this);

        empty = findViewById(R.id.iv_empty);
        recyclerviewTeams = (RecyclerView) findViewById(R.id.recyclerview_member);
        recyclerviewTeams.setLayoutManager(new LinearLayoutManager(this));
        recyclerviewTeams.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        mBlotterAdater = new MemberAdapter(this, memberCards);
        mAdapter = new RecyclerAdapterWithHF(mBlotterAdater);
        recyclerviewTeams.setVisibility(View.VISIBLE);
        recyclerviewTeams.setAdapter(mAdapter);
        mBlotterAdater.setOnItemClickListener(new MemberAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                goMemberInfo(position);
            }
        });

        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.sryt_swipe_listview);
        mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.app_title_color));
        mSwipeRefreshHelper = new SwipeRefreshHelper(mSwipeRefreshLayout);
        mSwipeRefreshHelper.setOnSwipeRefreshListener(new SwipeRefreshHelper.OnSwipeRefreshListener() {
            @Override
            public void onfresh() {
                currentNum = 1;
                isRefresh = true;
                memberCards.clear();
                requestMemberList();
            }
        });
        mSwipeRefreshHelper.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                if (mSwipeRefreshLayout.isRefreshing()) {
                    mSwipeRefreshHelper.loadMoreComplete(true);
                    return;
                }
                isLoad = true;
                ++currentNum;
                requestMemberList();
            }
        });
        requestMemberList();
        EventCenter.bindContainerAndHandler(getLifecycle(), new EventBusHandler() {
            public void onEventMainThread(MemberEvent event) {
                mAiJuTitleBarView.post(new Runnable() {
                    @Override
                    public void run() {
                        mSwipeRefreshHelper.autoRefresh();
                    }
                });
            }
        }).tryToRegisterIfNot();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mUser.getMPoints() == null ) {
            findViewById(R.id.rl_member_tip).setVisibility(View.VISIBLE);
            return;
        }
        if (mUser.getMPoints().isClose()){
            findViewById(R.id.rl_member_tip).setVisibility(View.GONE);
        }
        if (mUser.getMPoints().getStatus().equals("0")) {
            findViewById(R.id.rl_member_tip).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.rl_member_tip).setVisibility(View.GONE);
        }
    }

    /**
     * 请求会员列表
     */
    private void requestMemberList() {
        mDialogHelper.showLoadingProgressDialog();
        new MemberApi().memberList(mUser.getStoreId(), mUser.getToken(), String.valueOf(currentNum),
                String.valueOf(pageSize), new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        mDialogHelper.dismissProgressDialog();
                        T.ToastNetError();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        mDialogHelper.dismissProgressDialog();
                        DataJson json = new DataJson(response);
                        if (json.isSuccess()) {
                            List<Member> cards = new Gson().fromJson(json.getData().toString(), new TypeToken<List<Member>>() {
                            }.getType());
                            if (!Util.isEmpty(cards)) {
                                if (isRefresh) {
                                    memberCards.clear();
                                }
                                memberCards.addAll(cards);
                            }
                            mBlotterAdater.notifyDataSetChanged();
                            completeView(cards);
                        } else {
                            T.ToastShort(json.getMsg());
                        }
                    }
                });
    }

    /**
     * 加载完成视图动作
     *
     * @param cards
     */
    private void completeView(List<Member> cards) {
        //加载
        if (isLoad) {
            isLoad = false;
            mSwipeRefreshHelper.loadMoreComplete(true);
        }
        //刷新
        if (isRefresh) {
            isRefresh = false;
            mSwipeRefreshHelper.refreshComplete();
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        }

        if (cards.size() < pageSize) {
            mSwipeRefreshHelper.setLoadMoreEnable(false);
        } else {
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        }
        checkIfEmpty();
    }

    private void checkIfEmpty() {
        if (mBlotterAdater != null && mSwipeRefreshHelper != null) {
            final boolean emptyViewVisible = mBlotterAdater.getItemCount() == 0;
            if (emptyViewVisible) {
                //T.ToastShort("没有相关数据");
                empty.setVisibility(View.VISIBLE);
                recyclerviewTeams.setVisibility(View.GONE);
            } else {
                empty.setVisibility(View.GONE);
                recyclerviewTeams.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_member_add:
                goMemberCardAdd();
                break;
            case R.id.btn_member_card_add:
                goMemberPoints(); //积分设置
                break;
            case R.id.tv_member_tip:
                startActivity(MemberPointsSettingActivity.class);
                break;
            case R.id.iv_member_tip_close:
                mUser.getMPoints().setClose(true);
                findViewById(R.id.rl_member_tip).setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 会员详情
     */
    private void goMemberInfo(int position) {
        Intent intent = new Intent(this, MemberInfoCardsActivity.class);
        intent.putExtra("memberId", memberCards.get(position).getId());
        startActivity(intent);
    }

    /**
     * 积分设置
     */
    private void goMemberPoints() {
        startActivity(MemberPointsActivity.class);
    }

    /**
     * 新建会员
     */
    private void goMemberCardAdd() {
        startActivity(MemberAddActivity.class);
    }
}
